@echo off
setlocal

rem ================= 参数检查 =================
if "%~1"=="" (
  echo Usage: stopany.bat [ProcessName.exe | PID]
  exit /b 64
)

set "TARGET=%~1"

rem ================= 判断是 PID 还是 进程名 =================
call :IsNumber "%TARGET%"
if "%ERRORLEVEL%"=="0" (
  set "MODE=PID"
) else (
  set "MODE=IM"
)

echo Trying to terminate: %TARGET% (%MODE%)

rem ================= 第一次尝试：普通权限 =================
if "%MODE%"=="PID" (
  taskkill /F /T /PID "%TARGET%" >nul 2>&1
) else (
  taskkill /F /T /IM "%TARGET%" >nul 2>&1
)

if "%ERRORLEVEL%"=="0" (
  echo Terminated without elevation.
  endlocal & exit /b 0
)

rem ================= 检查是否还在 =================
if "%MODE%"=="PID" (
  tasklist /FI "PID eq %TARGET%" | find "%TARGET%" >nul 2>&1
) else (
  tasklist /FI "IMAGENAME eq %TARGET%" | find /i "%TARGET%" >nul 2>&1
)

if errorlevel 1 (
  echo Process not found. Nothing to do.
  endlocal & exit /b 0
)

echo Need elevation. Asking for admin...

rem ================= 第二次尝试：提权并等待完成 =================
if "%MODE%"=="PID" (
  powershell -NoProfile -ExecutionPolicy Bypass -Command ^
    "try { Start-Process taskkill -Verb RunAs -ArgumentList '/F','/T','/PID','%TARGET%' -Wait; exit $LASTEXITCODE } catch { exit 1223 }"
) else (
  powershell -NoProfile -ExecutionPolicy Bypass -Command ^
    "try { Start-Process taskkill -Verb RunAs -ArgumentList '/F','/T','/IM','%TARGET%' -Wait; exit $LASTEXITCODE } catch { exit 1223 }"
)

set "RC=%ERRORLEVEL%"

if "%RC%"=="0" (
  echo Terminated with elevation.
) else if "%RC%"=="1223" (
  echo UAC canceled by user.
) else (
  echo Failed. taskkill exit code: %RC%
)

endlocal & exit /b %RC%

rem ================= 工具函数：判断是否数字 =================
:IsNumber
rem 如果参数含有非数字字符，ERRORLEVEL 1；全是数字则 0
set "_s=%~1"
for /f "delims=0123456789" %%a in ("%_s%") do (exit /b 1)
exit /b 0
